package com.rubylong.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

@Slf4j
@RestController
@RequestMapping
public class TestController {

    @GetMapping("/findData/{name}")
    public String findData(@PathVariable String name) throws FileNotFoundException {
        File gridData = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "data/" + name + ".json");
        return readFileContent(gridData);
    }

    @GetMapping("/findTemplate/{name}")
    public String findTemplate(@PathVariable String name) throws FileNotFoundException {
        File gridTemplate = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "grf/" + name + ".grf");
        return readFileContent(gridTemplate);
    }

    private String readFileContent(File file) {
        StringBuffer sbf = new StringBuffer();
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
            String tempStr;
            while ((tempStr = reader.readLine()) != null) {
                sbf.append(tempStr);
            }
            reader.close();
            return sbf.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sbf.toString();
    }

}
